package org.xxpay.manage.agent.ctrl;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.xxpay.core.common.annotation.MethodLog;
import org.xxpay.core.common.constant.Constant;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.common.constant.RetEnum;
import org.xxpay.core.common.domain.BizResponse;
import org.xxpay.core.common.domain.XxPayPageRes;
import org.xxpay.core.common.domain.XxPayResponse;
import org.xxpay.core.common.exception.ServiceException;
import org.xxpay.core.common.util.AmountUtil;
import org.xxpay.core.common.util.DateUtil;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.entity.AgentAccount;
import org.xxpay.core.entity.AgentAccountHistory;
import org.xxpay.manage.common.ctrl.BaseController;
import org.xxpay.manage.common.service.CommonService;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author: dingzhiwei
 * @date: 17/12/6
 * @description:
 */
@RestController
@RequestMapping(Constant.MGR_CONTROLLER_ROOT_PATH + "/agent_account")
public class AgentAccountController extends BaseController {

    @Autowired
    private CommonService commonService;

    private static final MyLog _log = MyLog.getLog(AgentAccountController.class);

    /**
     * 查询账户信息
     * @return
     */
    @RequestMapping("/get")
    @ResponseBody
    public ResponseEntity<?> get(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Long agentId = getLongRequired(param, "agentId");
        AgentAccount agentAccount = commonService.agentAccountService.findByAgentId(agentId);
        return ResponseEntity.ok(XxPayResponse.buildSuccess(agentAccount));
    }

    /**
     * 代理商账户加钱
     * @return
     */
    @RequestMapping("/credit")
    @ResponseBody
    @MethodLog( remark = "代理商资金增加" )
    public ResponseEntity<?> credit(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);

        checkSecurityReq(param);  //敏感操作，用户安全认证校验

        Long agentId = getLongRequired(param, "agentId");
        String remark = getString(param, "remark");
        String amount = getStringRequired(param, "amount");         // 变更金额,前端填写的为元,可以为小数点2位
        Long amountL = new BigDecimal(amount.trim()).multiply(new BigDecimal(100)).longValue(); // // 转成分

        try {
            commonService.agentAccountService.changeBalanceAndInsertHistoryByPlat(agentId,  amountL, remark);
            return ResponseEntity.ok(BizResponse.buildSuccess());
        }catch (ServiceException e) {
            _log.error(e, "");
            return ResponseEntity.ok(BizResponse.build(e.getRetEnum()));
        }catch (Exception e) {
            _log.error(e, "");
            return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_UNKNOWN_ERROR));
        }
    }

    /**
     * 代理商账户减钱
     * @return
     */
    @RequestMapping("/debit")
    @ResponseBody
    @MethodLog( remark = "代理商资金减少" )
    public ResponseEntity<?> debit(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);

        checkSecurityReq(param);  //敏感操作，用户安全认证校验

        Long agentId = getLongRequired(param, "agentId");
        String remark = getString(param, "remark");
        String amount = getStringRequired(param, "amount");         // 变更金额,前端填写的为元,可以为小数点2位
        Long amountL = new BigDecimal(amount.trim()).multiply(new BigDecimal(100)).longValue(); // // 转成分

        try {
            commonService.agentAccountService.changeBalanceAndInsertHistoryByPlat(agentId,  (0 - amountL), remark);

            return ResponseEntity.ok(BizResponse.buildSuccess());
        }catch (ServiceException e) {
            _log.error(e, "");
            return ResponseEntity.ok(BizResponse.build(e.getRetEnum()));
        }catch (Exception e) {
            _log.error(e, "");
            return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_UNKNOWN_ERROR));
        }
    }

    /**
     * 查询资金流水列表
     * @return
     */
    @RequestMapping("/history_list")
    @ResponseBody
    public ResponseEntity<?> historyList(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        AgentAccountHistory agentAccountHistory = getObject(param, AgentAccountHistory.class);
        int count = commonService.agentAccountHistoryService.count(agentAccountHistory, getQueryObj(param));
        if(count == 0) return ResponseEntity.ok(XxPayPageRes.buildSuccess());
        List<AgentAccountHistory> agentAccountHistoryList = commonService.agentAccountHistoryService
                .select((getPageIndex(param) -1) * getPageSize(param), getPageSize(param), agentAccountHistory, getQueryObj(param));
        return ResponseEntity.ok(XxPayPageRes.buildSuccess(agentAccountHistoryList, count));
    }

    /**
     * 查询资金流水
     * @return
     */
    @RequestMapping("/history_get")
    @ResponseBody
    public ResponseEntity<?> historyGet(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Long id = getLongRequired(param, "id");
        AgentAccountHistory agentAccountHistory = commonService.agentAccountHistoryService
                .findById(id);
        return ResponseEntity.ok(XxPayResponse.buildSuccess(agentAccountHistory));
    }

    /**
     * 统计总数
     * @return
     */
    @RequestMapping("/agent_count")
    @ResponseBody
    public ResponseEntity<?> agentCount(HttpServletRequest request) {
        Map allMap = commonService.agentAccountService.agentCountBalance();
        JSONObject obj = new JSONObject();
        obj.put("agentCount", allMap.get("agentCount"));
        obj.put("balanceCount", allMap.get("balanceCount"));
        return ResponseEntity.ok(XxPayResponse.buildSuccess(obj));
    }

    @RequestMapping("/exportExcel")
    @ResponseBody
    public String exportExcel(HttpServletRequest request) throws Exception {

        JSONObject param = getJsonParam(request);
        AgentAccountHistory agentAccountHistory = getObject(param, AgentAccountHistory.class);
        if(agentAccountHistory == null) agentAccountHistory = new AgentAccountHistory();
        int count = commonService.agentAccountHistoryService.count(agentAccountHistory, getQueryObj(param));
        if(count > MchConstant.MAX_EXPORT_ROW) return RetEnum.RET_SERVICE_OUT_OF_RANGE_MAX_EXPORT_ROW.getMessage();
        List<AgentAccountHistory> agentAccountHistoryList = commonService.agentAccountHistoryService
                .select(0, MchConstant.MAX_EXPORT_ROW, agentAccountHistory, getQueryObj(param));

        List<List> excelData = new ArrayList<>();
        List header = Arrays.asList(new String[]{"代理商ID", "变更前余额（元）", "变更金额（元）", "变更后余额（元）", "业务类型", "业务类目", "业务订单", "备注", "创建时间"});
        excelData.add(header);
        for(AgentAccountHistory record : agentAccountHistoryList){
            List rowData = new ArrayList<>();
            rowData.add(record.getAgentId());
            rowData.add(AmountUtil.convertCent2Dollar(record.getBalance()+""));
            String prefix = record.getFundDirection() == MchConstant.FUND_DIRECTION_ADD ? "+" : "-";
            rowData.add(AmountUtil.convertCent2Dollar(prefix + record.getAmount()+""));
            rowData.add(AmountUtil.convertCent2Dollar(record.getAfterBalance()+""));
            rowData.add(MchConstant.convertBizType(record.getBizType(), MchConstant.SYSTYPE_AGENT));
            rowData.add(MchConstant.convertBizItem(record.getBizItem()));
            rowData.add(record.getOrderId());
            rowData.add(record.getRemark());
            rowData.add(DateUtil.date2Str(record.getCreateTime()));
            excelData.add(rowData);
        }
        super.writeExcelStream("代理商资金流水", excelData);

        return null;
    }

}
